import base64

from django.http import HttpResponse
from django.contrib.auth import authenticate, login

from lddns_web.models import Zone
from lddns_web.basicauth import logged_in_or_basicauth
from lddns_web.errors import (NoChangeError, NoHostError,
	WrongUserError, UpdateError)

def update(request):
	try:
		r = update_process(request)
	except UpdateError, e:
		r = HttpResponse(e.code)
	r.for_dyndns_client = True
	return r

@logged_in_or_basicauth(realm="Update")
def update_process(request):
	try:
		hostname = request.GET['hostname']
	except KeyError:
		raise Exception('Missing hostname')
	try:
		ip = request.GET['myip']
	except KeyError:
		ip = request.META['REMOTE_ADDR']
	
	# Find zone for hostname
	try:
		zone = Zone.objects.for_hostname(hostname)
	except Zone.DoesNotExist:
		raise NoHostError
	if zone.owner != request.user:
		raise WrongUserError
	store = zone.store()
	from lddns_web.dddatafile import APTRRecord
	store.update(hostname, rtype=APTRRecord, ip=ip, ttl=300)
	store.save()
	
	return HttpResponse('good %s %s' % (ip, hostname))
